/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dataentry;

import au.com.bytecode.opencsv.CSVReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

/**
 *
 * @author i.capurro
 */
public class FormFactory {
    
    private String path = null;
    private Form form = null;
    private char separador = ';';
    private String fname = null;
    
    public FormFactory(String file, String path) {
        this.path = path;
        this.fname = file;
    }
    
    private Form loadForm () throws FileNotFoundException, IOException, Exception {
        if (form == null) {
            FileReader read = new FileReader(path + "/" + fname + ".csv");
            CSVReader reader = new CSVReader(read, separador);
            List myEntries = reader.readAll();
            Iterator it = myEntries.iterator();
            form = new Form(fname);
            while (it.hasNext()) {
                String[] vals = (String[]) it.next();
                Question aux = null;
                if (Integer.valueOf(vals[1]) > 1) {
                    aux = new MultipleQ(vals[0], Integer.valueOf(vals[1]));
                } else {
                    aux = new UniqueQ(vals[0]);
                }
                // vals[2] son las validationRules
                if (!vals[2].isEmpty()) {
                    aux.setQuestionRule(vals[2]);
                }
                // vals[3] son las quantityRules
                if (!vals[3].isEmpty()) {
                    aux.setQuantityRule(vals[3]);
                }
                // vals[4] son las questionRules
                if (!vals[4].isEmpty()) {
                    aux.setValueRule(vals[4]);
                }
                if (!vals[5].isEmpty()) {
                    Boolean e = Boolean.parseBoolean(vals[5]);
                    aux.setNotEmpty(e);
                }
                if (!vals[6].isEmpty()) {
                    Boolean d = Boolean.parseBoolean(vals[6]);
                    aux.setNotAcceptDuplicateValues(d);
                }
                if (!vals[7].isEmpty()) {
                    String funnelQ = vals[7];
                    Question q = form.getQuestion(funnelQ);
                    aux.setFunnelQuestion(q);
                }
                form.insertQuestion(aux);
            }
        }
        
        return form;
    }
    
    public Form getForm() throws FileNotFoundException, IOException, Exception {
        if (form == null) {
            form = loadForm();
        }
        return form;
    }
    
    
}
